package com.dmall.opening.up.records;

import com.dmall.opening.up.core.Order;
import com.dmall.opening.up.records.dao.mysql.mybatis.mapper.OrderMapper;
import com.dmall.opening.up.records.exception.BizException;
import org.joda.time.DateTime;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public abstract class OrderRecord implements Order {

    protected Long id;

    protected UserRecord user;

    protected Status status;

    protected Referer referer;

    protected Map<String, Object> ext;

    protected DateTime created;

    protected DateTime modified;

    protected List<ItemRecord> items;

    @Resource
    protected OrderMapper mapper;

    @Override
    public Optional<Item> findItem(Long itemId) {
        final Item item = mapper.findItemById(this.id, itemId);
        if (item == null) {
            return Optional.empty();
        }
        ((ItemRecord) item).order = this;
        return Optional.of(item);
    }

    public static class ItemRecord implements Order.Item {

        Long id;

        String code;

        boolean returned;

        transient OrderRecord order;

        @Resource
        protected OrderMapper mapper;

        @Override
        public void return_() {
            ensureReturnNotDuplicated();
            ensureNotBeyondThePeriod();
            this.returned = true;
            final int affected = mapper.return_(this);
            if (affected != 1) {
                throw BizException.unsupportedOperation();
            }
        }

        private void ensureReturnNotDuplicated() {
            if (returned) {
                throw BizException.unsupportedOperation();
            }
        }

        private void ensureNotBeyondThePeriod() {
            final boolean beyondThePeriod = order.created.plusDays(30).isBeforeNow();
            if (beyondThePeriod) {
                throw BizException.returnBeyondThePeriod();
            }
        }
    }
}
